using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace HTCollections.Custom
{
    /// <summary>
    /// 数组相关工具方法
    /// </summary>
    public static class ArrayUtil
    {
        /// <summary>
        /// 扩容
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void Resize<T>(ref T[] array, int newCapacity)
        {
            T[] newArray = new T[newCapacity];
            Array.Copy(array, 0, newArray, 0, array.Length);
            array = newArray;
        }

        /// <summary>
        /// 查询元素索引
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int IndexOf<T>(T[] array, T value, EqualityComparer<T> comparer)
        {
            for (int i = 0, length = array.Length; i < length; i++)
            {
                if (comparer.Equals(array[i], value))
                    return i;
            }

            return -1;
        }

        /// <summary>
        /// 获取扩容后的容量
        /// </summary>
        /// <param name="currentSize">当前容量</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int GetCapacity(int currentSize)
        {
            for (int i = 0, length = CapacitySizeArray.Length; i < length; i++)
            {
                var capacity = CapacitySizeArray[i];
                if (capacity >= currentSize)
                    return capacity + 1;
            }

            throw new Exception("Capacity is too big");
        }

        static readonly int[] CapacitySizeArray = new int[]
        {
            3,
            15,
            63,
            255,
            1023,
            2047,
            4095,
            16383,
            65535,
            131071,
            262143,
            524287,
            1048575,
            2097151,
            4194303,
            8388607,
            16777215,
            33554431,
            67108863,
            134217727,
            268435455,
            536870912,
            1073741823,
        };
    }
}